﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using PARK.Common.Core.Manager;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Consumer.Entity;
using PARK.Consumer.Entitys.Dto.ConsumRefund;
using PARK.Consumer.Interfaces.ConsumRefund;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.JsonSerialization;
using PARK.System.Interfaces.System;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace PARK.Consumer
{
    /// <summary>
    /// 退款服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Consum", Name = "ConsumRefund", Order = 200)]
    [Route("api/consum/[controller]")]
    public class ConsumRefundService : IConsumRefundService, IDynamicApiController, ITransient
    {

        private readonly ISqlSugarRepository<ConsumRefundEntity> _consumRefundRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;
        private readonly ISysConfigService _sysConfigService;

        /// <summary>
        /// 初始化一个<see cref="ConsumRefundService"/>类型的新实例
        /// </summary>
        public ConsumRefundService(
            ISqlSugarRepository<ConsumRefundEntity> consumRefundRepository,
            IUserManager userManager,
            ISysConfigService sysConfigService)
        {
            _consumRefundRepository = consumRefundRepository;
            _db = _consumRefundRepository.Context;
            _userManager = userManager;
            _sysConfigService = sysConfigService;
        }

        /// <summary>
        /// 获取充值管理
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<ConsumRefundEntity>().FirstAsync(p => p.taskId == id);
            var output = entity.Adapt<ConsumRefundInfoOutput>();
            return output;
        }
        /// <summary>
		/// 获取退款列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ConsumRefundListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "AuditDate" : input.sidx;
                List<string> queryBillDate = input.billDate != null ? input.billDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startBillDate = queryBillDate != null ? Ext.GetDateTime(queryBillDate.First()) : null;
                DateTime? endBillDate = queryBillDate != null ? Ext.GetDateTime(queryBillDate.Last()) : null;
                var data = await _db.Queryable<ConsumRefundEntity>()
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))//权限
                    .WhereIF(queryBillDate != null, p => p.AuditDate >= new DateTime(startBillDate.ToDate().Year, startBillDate.ToDate().Month, startBillDate.ToDate().Day, 0, 0, 0))
                    .WhereIF(queryBillDate != null, p => p.AuditDate <= new DateTime(endBillDate.ToDate().Year, endBillDate.ToDate().Month, endBillDate.ToDate().Day, 23, 59, 59))
                    .WhereIF(!string.IsNullOrEmpty(input.billStatus), p => p.billStatus.Equals(input.billStatus))
                    .WhereIF(!string.IsNullOrEmpty(input.keyword), p => p.JobNo.Contains(input.keyword) || p.ReallName.Contains(input.keyword) || p.CardNo.Contains(input.keyword))
                    .WhereIF(!string.IsNullOrEmpty(input.cardNo), p => p.CardNo.Equals(input.cardNo))
                    .WhereIF(!string.IsNullOrEmpty(input.userId), p => p.CreateUser.Equals(input.userId))
                    .Select(t => new ConsumRefundListOutput
                    {
                        taskId = t.taskId,
                        EmployeeId = t.EmployeeId,
                        ReallName = t.ReallName,
                        JobNo = t.JobNo,
                        CardNo =t.CardNo,
                        CatCardNo =t.CatCardNo,
                        DepartId = t.DepartId,
                        DepartName = t.DepartName,
                        CompanyId =t.CompanyId,
                        CompanyName=t.CompanyName,
                        CreateDate =t.CreateDate,
                        CreateUser=t.CreateUser,
                        CreateUserName=t.CreateUserName,
                        DbDate =t.DbDate,                       
                        RefundDate=t.RefundDate,
                        rechargeId=t.rechargeId,                        
                        refund_id=t.refund_id,                        
                        out_refund_no=t.out_refund_no,
                        out_trade_no=t.out_trade_no,
                        transaction_id = t.transaction_id,
                        totalAmt = t.totalAmt,
                        refundAmt = t.refundAmt,
                        IsNeedRefund =t.IsNeedRefund,
                        IsRefund = t.IsRefund,
                        IsAny = t.IsAny,
                        Summary = t.Summary,
                        refundStatus = t.refundStatus,
                        AuditDate = t.AuditDate,
                        billStatus =t.billStatus,
                        billStatusName =t.billStatusName
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<ConsumRefundListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }
    }
}
